import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { getCookie } from "@/utils/cookie";
import { Message } from "element-ui";
import { Toast } from "vant";
import { isPhone } from "@/utils"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '',
    component: Home,
    children: [
      {
        path: "",
        redirect: "register",
      },
      {
        path: 'register',
        component: () => import(/* webpackChunkName: "register" */ '../views/register/Register.vue'),
        name: 'Register',
        meta: {
          title: "index",
          showTop: true,
          showBottom: true,
          index: 2,
          isToken: false,
        },
      },
      {
        path: 'homePage',
        component: () => import(/* webpackChunkName: "homePage" */ '../views/home/HomePage.vue'),
        name: 'HomePage',
        meta: {
          title: "home",
          showTop: true,
          showBottom: false,
          index: 3,
          isToken: true,
        },
      },
    ]
  },

]

/**
 * 重写路由的push方法
 * 解决，相同路由跳转时，报错
 */

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const router = new VueRouter({
  routes,
  scrollBehavior(to, from, saveTop) {
    if (saveTop) {
      return saveTop;
    } else {
      return { x: 0, y: 0 };
    }
  }
})

// 路由权限控制
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  let isLogin = getCookie("token");
  let isToken = to.meta.isToken;
  if (isToken) {
    if (!isLogin) {
      if (isPhone(650)) {
        Toast("您还没有登录!");
        next("/");
      } else {
        Message.error("您还没有登录!")
        next("/");
      }
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router
